<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>实现元素平滑上升</title>
</head>
    <style>
        div{
            width: 750px;
            height: 300px;
            margin:  30px auto;
            background-color: aqua;
            font-size: 200px;
            text-align: center;
            color: white;
        }
    </style>
<body>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
    <div>7</div>
    <div>8</div>
    <div>9</div>
    <div>10</div>
    <script>
        const DISTANCE = 150;
        const map = new WeakMap();
        const ob = new IntersectionObserver((entries)=>{
            for(const entry of entries){
                if(entry.isIntersecting){
                    // 改元素和视口相交

                    // 播放该元素的动画
                    const animation = map.get(entry.target)
                    if(animation){
                        animation.play();
                        ob.unobserve(entry.target);
                    }
                }
                console.log(entry)
            }
        })
        function isBelowViwport(ele){
            const rect = ele.getBoundingClientRect();
            return rect.top-DISTANCE>window.innerHeight;
        }
        const divs = document.querySelectorAll('div');
        for(var i=0;i<divs.length;i++){
            const ele= divs[i];
            if(!isBelowViwport(ele)){
                continue ;
            }

            const animation = ele.animate([
                {transform:`translateY(${DISTANCE}px)`,opacity:0.5},
                {transform:'translateY(0)',opacity:1},
            ],{duration:500,easing:'ease-in-out',fill:'forwards'});
            animation.pause();
            ob.observe(ele);
            map.set(ele,animation);
        }
    </script>
</body>
</html>